<template>
  <div class="wrapper">
    <div class="tags">  
      <vuedraggable class="vue-draggable" tag="ul" v-model="list"  animation="300" draggable=".draggable-item" @start="onDragStart" @end="onDragEnd">
        <!-- 拖拽元素 -->
        <li v-for="(item, index) in list" :key="item" class="draggable-item">
          <el-tag :key="item" closable :disable-transitions="false" @close="tagClose(index)">{{item}}</el-tag>
        </li>
        <el-input
          class="input-new-tag"
          v-if="inputVisible"
          v-model="inputValue"
          ref="saveTagInput"
          size="small"
          @keyup.enter.native="tagInputConfirm"
          @blur="tagInputConfirm"
        >
        </el-input>
        <el-button v-if="!isMaxHidden && !inputVisible" class="button-new-tag" size="small" @click="tagShowInput">+ 添加</el-button>
        <el-button v-if="isUseTemp" style="margin-left:10px;"  icon="el-icon-notebook-2" size="mini" @click="tapTemp">使用模板</el-button>
      </vuedraggable>
    </div>
  </div>
</template>
<style scoped>
.vue-draggable{display: flex;flex-wrap: wrap;align-items: center;padding:0;}
.draggable-item{margin-right: 10px;}
.draggable-item:hover{cursor:move;}
.button-new-tag {height: 32px;line-height: 30px;padding-top: 0;padding-bottom: 0;}
.input-new-tag {width: 90px;margin-right: 10px;vertical-align: bottom;}
</style>
<script>
import vuedraggable from 'vuedraggable'

export default {
  name: 'danFormTags',
  components: { vuedraggable },
  props: {
    value: {
      type: Array,
      default () {
        return []
      }
    },
    // 限制数量
    limit: {
      type: Number,
      default: 99
    },
    isUseTemp:{
      type: Boolean,
      default(){
        return false
      }
    }
  },

  data () {
    return {
      inputValue:'',
      inputVisible:false
    }
  },

  computed: {
    list: {
      get () {
        return this.value
      },
      set (val) {
        // 同步v-model
        this.$emit('update:value', val);
      }
    },
    // 控制达到最大限制时隐藏上传按钮
    isMaxHidden () {
      return this.list.length >= this.limit
    }
  },
  watch: {
    /*value: {
      handler (val) {
        
      },
      deep: true
    }*/
  },

  mounted () {
    
  },

  methods: {
    onDragStart (e) {
      e.target.classList.add('hideShadow')
    },
    onDragEnd (e) {
      e.target.classList.remove('hideShadow')
    },
    tagClose(index){
      this.list.splice(index, 1);
    },
    tagShowInput() {
      this.inputVisible = true;
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    tagInputConfirm() {
        let inputValue = this.inputValue.trim();
        inputValue = inputValue.replace(/,/g,'');
        if (inputValue && this.list.indexOf(inputValue) < 0) {
          this.list.push(inputValue);
        }
        this.inputVisible = false;
        this.inputValue = '';
    },
    tapTemp(){
      this.$emit('tapTemp');
    }
  }
}
</script>


